package club.justwill.single.persistence.support;

import club.justwill.single.Tools;
import club.justwill.single.model.SecurityToken;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Projections;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 * Created by xiangnan on 10/28/15.
 */
public class BaseDao<T extends Jpo> {

	@PersistenceContext
	protected EntityManager em;

	protected Session getSession() {
		return (Session) em.getDelegate();
	}

	@Autowired
	@Qualifier("tools")
	private ObjectFactory<Tools> toolsFactory;

	protected Tools getTools() {
		return toolsFactory.getObject();
	}

	protected long countResults(Criteria criteria) {
		criteria.setProjection(Projections.rowCount());
		long count = ((Long) criteria.uniqueResult()).longValue();
		criteria.setProjection(null)
				.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
		return count;
	}

	public void save(T obj, SecurityToken token) {
		obj.updateAudit(token);
		em.persist(obj);
	}

	public void update(T obj, SecurityToken token) {
		obj.updateAudit(token);
		em.merge(obj);
	}

	public void delete(T obj) {
		em.remove(obj);
	}
}
